<template>
  <el-container class="home-container">
    <!-- 侧边栏 -->
    <el-aside width="200px" class="aside">
      <el-menu 
        default-active="1" 
        class="el-menu-vertical-demo"
        @select="handleMenuSelect"
        background-color="#304156"
        text-color="#fff"
        active-text-color="#ffd04b"
      >
        <el-menu-item index="1">
          <el-icon><Home /></el-icon>
          <span>首页</span>
        </el-menu-item>
        <el-menu-item index="2">
          <el-icon><ShoppingCart /></el-icon>
          <span>订单管理</span>
        </el-menu-item>
        <el-menu-item index="3">
          <el-icon><Goods /></el-icon>
          <span>菜品管理</span>
        </el-menu-item>
        <el-menu-item index="4">
          <el-icon><Shop /></el-icon>
          <span>店铺管理</span>
        </el-menu-item>
        <el-menu-item index="5">
          <el-icon><User /></el-icon>
          <span>用户管理</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <el-header class="header">
        <div class="user-info">
          <span>欢迎回来：{{ userInfo.userName || userInfo.userPhone }}</span>
          <el-button type="text" @click="handleLogout">退出登录</el-button>
        </div>
      </el-header>
      
      <el-main class="main">
        <!-- 统计卡片 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div slot="header">今日销售额</div>
              <div class="stat-value">{{ todaySales }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div slot="header">今日订单数</div>
              <div class="stat-value">{{ todayOrders }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div slot="header">热销菜品</div>
              <div class="stat-value">{{ hotFood }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div slot="header">今日用户量</div>
              <div class="stat-value">{{ todayUsers }}</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 销售趋势图 -->
        <el-card class="chart-card" style="margin-top: 20px;">
          <div slot="header">销售趋势</div>
          <el-row>
            <el-col :span="24">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleDateChange"
                style="margin-bottom: 20px;"
              ></el-date-picker>
              <div class="chart-container">
                <canvas id="salesChart" width="400" height="200"></canvas>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { Home, ShoppingCart, Goods, Shop, User } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import Chart from 'chart.js/auto';

// 获取全局实例和路由
const { proxy } = getCurrentInstance();
const router = useRouter();

// 状态管理
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'));
const todaySales = ref('¥0');
const todayOrders = ref(0);
const hotFood = ref('暂无');
const todayUsers = ref(0);
const dateRange = ref([]);
let salesChart = null;

// 菜单切换
const handleMenuSelect = (index) => {
  switch(index) {
    case '2': router.push('/order'); break;
    case '3': router.push('/food'); break;
    case '4': router.push('/store'); break;
    case '5': router.push('/user'); break;
  }
};

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('userInfo');
  router.push('/login');
  ElMessage.success('已退出登录');
};

// 获取统计数据
const getStatData = async () => {
  const today = new Date().toISOString().split('T')[0];
  
  try {
    // 今日销售额
    const salesRes = await proxy.$axios.get('/orderlist/queryallpriceByDate', {
      params: { date: today }
    });
    todaySales.value = `¥${salesRes.totalprice || 0}`;

    // 今日订单数
    const orderRes = await proxy.$axios.get('/orderlist/countByDate', {
      params: { date: today }
    });
    todayOrders.value = orderRes.count || 0;

    // 热销菜品
    const foodRes = await proxy.$axios.get('/orderlist/getGoodsTotalCountByDay', {
      params: { date: today }
    });
    if (foodRes.data) {
      const foodArr = Object.entries(foodRes.data);
      foodArr.sort((a, b) => b[1] - a[1]);
      hotFood.value = foodArr[0]?.[0] || '暂无';
    }

    // 今日用户量
    const userRes = await proxy.$axios.get('/user/countByDate', {
      params: { date: today }
    });
    todayUsers.value = userRes.count || 0;

  } catch (error) {
    ElMessage.error('获取数据失败');
  }
};

// 初始化图表
const initChart = () => {
  const ctx = document.getElementById('salesChart').getContext('2d');
  
  // 销毁现有图表
  if (salesChart) {
    salesChart.destroy();
  }
  
  // 模拟数据 - 实际项目中从接口获取
  salesChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
      datasets: [{
        label: '销售额',
        data: [12000, 19000, 15000, 22000, 28000, 25000],
        borderColor: '#409eff',
        backgroundColor: 'rgba(64, 158, 255, 0.1)',
        tension: 0.3,
        fill: true
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
};

// 日期范围变化
const handleDateChange = (range) => {
  if (range) {
    // 实际项目中根据日期范围重新获取数据并更新图表
    ElMessage.success(`已选择日期范围: ${range[0]} 至 ${range[1]}`);
  }
};

onMounted(() => {
  getStatData();
  initChart();
});
</script>

<style scoped>
.home-container {
  height: 100vh;
}
.aside {
  background-color: #304156;
}
.header {
  background-color: #fff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.user-info {
  display: flex;
  gap: 20px;
  align-items: center;
}
.stat-card {
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #165DFF;
  padding: 10px 0;
}
.chart-container {
  width: 100%;
  height: 400px;
}
</style>
